package com.wjpeng.wms.service.impl;

import com.wjpeng.wms.domain.Employee;
import com.wjpeng.wms.domain.Permission;
import com.wjpeng.wms.mapper.EmployeeMapper;
import com.wjpeng.wms.mapper.PermissionMapper;
import com.wjpeng.wms.query.EmployeeQueryObject;
import com.wjpeng.wms.service.IEmployeeService;
import com.wjpeng.wms.util.MD5;
import com.wjpeng.wms.util.PageResult;
import com.wjpeng.wms.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.util.Collections;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private PermissionMapper permissionMapper;



    @Override
    public void saveOrUpdate(Employee d, Long[] roleIds) {
        if(d.getId() == null){
            String newpwd = MD5.encoder(d.getPassword());
            d.setPassword(newpwd);
            employeeMapper.insert(d);
        }else{
            employeeMapper.deleteReation(d.getId());
            employeeMapper.updateByPrimaryKey(d);
        }

        if(roleIds != null){
            for (Long roleId : roleIds) {
                employeeMapper.insertReation(d.getId(),roleId);
            }
        }
    }

    @Override
    public void delete(Long id) {
        if(id != null){
            employeeMapper.deleteReation(id);
            employeeMapper.deleteByPrimaryKey(id);
        }
    }

    @Override
    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> list() {
        return employeeMapper.selectAll();
    }

    @Override
    public PageResult result(EmployeeQueryObject qo) {
        Integer count = employeeMapper.queryCount(qo);
        if(count == 0){
            return new PageResult(Collections.EMPTY_LIST,0,1,0);
        }
        return new PageResult(employeeMapper.queryLimit(qo),count,qo.getCurrentPage(),qo.getPageSize());
    }

    //登陆信息
    @Override
    public void login(String username, String password) {
        //密码记得加密
        Employee employee = employeeMapper.selectByInfo(username,MD5.encoder(password));
        if (employee==null) {
            //账号密码错误则报一个异常
            throw new RuntimeException("账号密码不匹配");
        }

        //把登陆成功的用户存入一个session中
        UserContext.setCurrentUser(employee);


        //如果是非超级管理员,把当前用户的权限存入session中
        if(!employee.getAdmin()){
            //获取权限表达式expression
            List<String> expressions = permissionMapper.selectByEmployeeId(employee.getId());
            UserContext.setExpression(expressions);
        }
    }
}
